import streamlit as st
import base64
from globals import (
    LOGO, MAIN_PATH, 
    MAIN_PAGE_NAME, 
    PROFILE_PATH, 
    PROFILE_PAGE_NAME, 
    PRODUCTS_PATH, 
    PRODUCTS_PAGE_NAME
)
from database.queries.user_orm import SynOrmUserQueries
from widgets.authenticator import Authenticator


# It's a hack, actually. 
# In this moment there is no other ways to render svg im md
def render_logo():
    st.markdown(
        """
        <style>
        .logo {
            width: 100%;
            height: auto;
            padding: 0px;
        }
        </style>
        """,
        unsafe_allow_html=True,
    )
    
    
    # Function to convert image to base64
    def img_to_base64(image_path):
        with open(image_path, "rb") as img_file:
            return base64.b64encode(img_file.read()).decode()
        

    # Load and display sidebar image
    img_base64 = img_to_base64(LOGO)
    st.markdown(
        f"<img src='data:image/svg+xml;base64,{img_base64}' class='logo'>",
        unsafe_allow_html=True,
    )
    st.divider()


def __get_authenticator():
    if "authenticator" not in st.session_state:
        st.session_state["authenticator"] = Authenticator()
    return st.session_state["authenticator"]


def authenticated_menu():
    authenticator: Authenticator = __get_authenticator()
    if "username" not in st.session_state:
        return
    
    if "first_enter" not in st.session_state:
        st.session_state["first_enter"] = True
    if st.session_state["first_enter"]:
        name = SynOrmUserQueries.get_user_by_username(
            st.session_state["username"],
        ).name
        if name != "":
            st.toast(f"Приветствуем, {name}!", icon="🎊")
        else:
            st.toast("Приветствуем!", icon="🎊")
        st.session_state["first_enter"] = False
    
    with st.sidebar:
        render_logo()
        st.page_link(MAIN_PATH, label=MAIN_PAGE_NAME, icon="🏠")
        st.page_link(PROFILE_PATH, label=PROFILE_PAGE_NAME, icon="👤")
        st.page_link(PRODUCTS_PATH, label=PRODUCTS_PAGE_NAME, icon="😋")
        st.divider()
        authenticator.logout_button()
    
    
def unauthenticated_menu():
    with st.sidebar:
        st.page_link(MAIN_PATH, label="Авторизация", icon="🔐")
    
    
def menu():
    authenticator: Authenticator = __get_authenticator()
    if authenticator.is_authorized():
        authenticated_menu()
        return
    unauthenticated_menu()
    
    
def menu_with_redirect():
    authenticator: Authenticator = __get_authenticator()
    if not authenticator.is_authorized():
        st.switch_page(MAIN_PATH)
    menu()
    